<template>
  <q-table
    class="card-radius my-table"
    wrap-cells
    :rows="row"
    :columns="col"
    :rows-per-page-options="[0]"
  >
    <template v-slot:body-cell-doc_name="props">
      <q-td :props="props">
        <div class="row justify-start items-center">
          <template v-if="props.row.file">
            <q-icon name="attach_file" /><a
              :href="djangoUrl + props.row.file"
              target="_blank"
              >{{ props.row.doc_name }}</a
            >
          </template>
          <template v-else>
            {{ props.row.doc_name }}
          </template>
        </div>
      </q-td>
    </template>
    <template v-slot:body-cell-complete="props">
      <q-td
        :class="{
          fail: props.value == 'Not Completed',
        }"
      >
        {{ props.value }}
      </q-td>
    </template>
  </q-table>
</template>
<script setup lang="ts">
import { PartsEDoc } from 'src/services/type';
import { PartsEDocFilter } from 'src/services/partsEDocService';
import { ref } from 'vue';
import { listPartsEDocs } from 'src/services/partsEDocService';
import { resolveDjangoUrl } from 'src/boot/axios';
import { formatDateTimeString } from 'src/utils/dateUtils';

const props = defineProps<{
  // filter?: Partial<PartsEDocFilter>
  part_ids: number[];
  doc_name: string;
}>();
const djangoUrl = resolveDjangoUrl();

const row = ref<PartsEDoc[]>();
const align = 'left';
const col = [
  {
    name: 'stock_code',
    field: 'stock_code',
    label: 'Stock Code',
    sortable: true,
    align,
  },
  {
    name: 'serial_no',
    field: 'serial_no',
    label: 'Serial No',
    sortable: true,
    align,
  },
  {
    name: 'doc_name',
    field: 'doc_name',
    label: 'Doc Name',
    sortable: true,
    align,
  },
  {
    name: 'version',
    field: 'version',
    label: 'Version',
    sortable: true,
    align,
  },
  {
    name: 'created',
    field: 'created',
    label: 'Created',
    format: (v) => formatDateTimeString(v),
    sortable: true,
    align,
  },

  {
    name: 'complete',
    field: 'complete',
    label: 'Complete',
    format: (v) => (v == 1 ? 'Completed' : 'Not Completed'),
    align,
  },
];

async function fetchData() {
  row.value = [];

  for (let index in props.part_ids) {
    const filter = {
      parts: props.part_ids[index],
      doc_name: props.doc_name,
    } as Partial<PartsEDocFilter>;
    const res = await listPartsEDocs(filter);
    console.log(res);
    row.value = [...row.value, ...res];
  }
}

if (props.part_ids && props.doc_name) {
  fetchData();
}
</script>
